package com.example.Lezedata.ui.activity.pay;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimatedImageDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.Lezedata.R;
import com.example.Lezedata.dataManager.GBUserManager;
import com.example.Lezedata.dataModel.BidDetailManager;
import com.example.Lezedata.dataModel.GoodsInfoModel;
import com.example.Lezedata.dataModel.GoodsProjectModel;
import com.example.Lezedata.net.GBError;
import com.example.Lezedata.net.GBNetRequest;
import com.example.Lezedata.net.ServerResponseObserver;
import com.example.Lezedata.ui.activity.address.Address_addVc;
import com.example.Lezedata.ui.activity.baseClass.GBBaseVc;
import com.example.Lezedata.ui.activity.common.TransitionPage;
import com.example.Lezedata.ui.activity.goods.GoodsNameView;
import com.example.Lezedata.ui.activity.person.DepositVc;
import com.example.Lezedata.ui.activity.setting.PinSettingVc;
import com.example.Lezedata.ui.fragment.commonfragment.AlertFragment;
import com.example.Lezedata.ui.fragment.commonfragment.TransactionPinView;
import com.example.Lezedata.util.GBUtil;
import com.example.Lezedata.util.RadiusBackgroundSpan;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import bid.Bid;

public class PayVc extends GBBaseVc {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay_vc;
    }

    @Override
    public CharSequence title() {
        return getResources().getString(R.string.Pay);
    }

    String bid ;
    int bidCount ;
    String price;

    ImageView goodsIcon;
    GoodsNameView goodsNameView;
    TextView buyNumber;
    TextView total;
    TextView wallet;
    TextView payStack;
    TextView countdown;
    TextView payButton;
    TextView deposit;

    TextView wal_sel;
    TextView pay_sel;

    GoodsProjectModel model = GoodsProjectModel.testGoodsProjectModel();
    GoodsInfoModel infoModel = model.infoModel;

    Bid.PayType payType = Bid.PayType.PT_NONE;
    int dueTime = 600;
    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            dueTime--;
            if (dueTime <= 0){
                handler.removeCallbacks(runnable);
                finish();
                return;
            }
            refreshTime(dueTime);
            handler.postDelayed(this, 1000);
        }
    };

    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        getData();
        findView();
        setData();
        addAction();
    }

    void findView(){
        goodsIcon = findViewByTag("goodsIcon");
        goodsNameView = findViewByTag("goodsNameView");
        buyNumber = findViewByTag("buyNumber");
        total = findViewByTag("total");
        wallet = findViewByTag("wallet");
        payStack = findViewByTag("payStack");
        countdown = findViewByTag("countdown");
        payButton = findViewByTag("payButton");
        deposit = findViewByTag("deposit");
        wal_sel = findViewByTag("wal_sel");
        pay_sel = findViewByTag("pay_sel");
    }

    void addAction(){
        payButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });

        LinearLayout layout = (LinearLayout) wallet.getParent();
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshPayType(Bid.PayType.PT_BALANCE);
            }
        });

        LinearLayout layout1 = (LinearLayout) payStack.getParent();
        layout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshPayType(Bid.PayType.PT_BANK);
            }
        });

        deposit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpActivity(DepositVc.class);
            }
        });
    }

    void submit(){
        boolean hasPinPsd = GBUserManager.instance().hasPIN;
        if (!hasPinPsd){
            setPinPsd();
            return;
        }
        final TransactionPinView ms = TransactionPinView.newInstance();
        ms.inputListener = new TransactionPinView.InputListener() {
            @Override
            public void InputComplete(String text) throws NoSuchAlgorithmException {
                ms.dismiss();
                pay(text);
            }
        };
        ms.show(getSupportFragmentManager(),"TransactionPinView");
    }

    void setPinPsd(){
        AlertFragment fragment = new AlertFragment();
        fragment.text = "Please set your PIN";
        fragment.okListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpActivity(PinSettingVc.class);
            }
        };
        fragment.show(getSupportFragmentManager(),"alert");
    }

    void pay(String pwd) throws NoSuchAlgorithmException {
        Bid.BidRequest request = Bid.BidRequest.newBuilder()
                .setBidCount(bidCount)
                .setBidId(bid)
                .setPayType(payType)
                .setTransPw(GBUtil.getSHA256(pwd))
                .build();
//        GBNetRequest.stubUser().bid(request, ServerResponseObserver.observer(new ServerResponseObserver.requestListener<Bid.BidResponse>() {
//            @Override
//            public void complete(Bid.BidResponse value, GBError error) {
//                if (error == null){
//                    finish();
//                    Intent intent;
//                    if (value.getNeedExpressAddress()){
//                        intent = new Intent(mContext, Address_addVc.class);
//                        intent.putExtra("isPay",true);
//                    }else {
//                        intent = new Intent(mContext, TransitionPage.class);
//                        intent.putExtra(TransitionPage.Key_title,"Payment Successfully!");
//                        intent.putExtra(TransitionPage.Key_image,R.drawable.pay_little_successfully);
//                    }
//                    jumpActivityIntent(intent);
//                }
//            }
//        }));
    }

    void refreshPayType(Bid.PayType type){
        payType = type;
        int resId_nol = R.drawable.login_checkbox_default;
        int resId_sel = R.drawable.login_checkbox_selected;

        switch (payType){
            case PT_BALANCE:{
                wal_sel.setBackground(getResources().getDrawable(resId_sel));
                pay_sel.setBackground(getResources().getDrawable(resId_nol));
            }
                break;
            case PT_BANK:{
                pay_sel.setBackground(getResources().getDrawable(resId_sel));
                wal_sel.setBackground(getResources().getDrawable(resId_nol));
            }
                break;
        }
    }

    void setData(){
        BidDetailManager.getBidInfoForId(bid, new BidDetailManager.OnLoadBidDetailDataComplete() {
            @Override
            public void infoResponse(final Bid.BidDetailResponse response) {
                BidDetailManager.getGoodsInfoForId(response.getGoodsId(), new BidDetailManager.OnLoadDataComplete() {
                    @Override
                    public void infoResponse(Bid.GoodsInfo goodsInfo) {
                        refreshData(response,goodsInfo);
                    }
                });
            }
        });

    }

    void refreshData(Bid.BidDetailResponse response,Bid.GoodsInfo goodsInfo){
        GBUtil.setGoodsImage(goodsIcon,goodsInfo.getImgUrl());

        goodsNameView.setModelForNameWithDetail(goodsInfo.getName(),goodsInfo.getDesc());

        String num = String.valueOf(bidCount);
        String bidNum = String.format("Bought:  %s bids",num);
        int index = bidNum.indexOf(num);
        SpannableString spannableString = GBUtil.textAddColor(bidNum,getResources().getColor(R.color.app_color_main),index,index+num.length());
        buyNumber.setText(spannableString);

        wallet.setText(String.format("Wallet(%s)",GBUtil.moneyToString(GBUserManager.instance().balance)));
        refreshPayType(Bid.PayType.PT_BALANCE);

        total.setText(String.format("₦ %s",price));

        refreshTime(dueTime);
        runnable.run();
    }

    void refreshTime(int time){

        int min = time/60;
        int sec = time%60;

        String str1 = String.format("%02d",min);
        String str2 = String.format("%02d",sec);

        String str5 = String.format("%s:%s",str1,str2);

        int index1 = 0;
        int index2 = str1.length() + 1;

        SpannableString spannableString = new SpannableString(str5);
        addBackgroundColorToText(spannableString,index1,str1.length());
        addBackgroundColorToText(spannableString,index2,str2.length());
        countdown.setText(spannableString);
    }

    void addBackgroundColorToText (SpannableString spannableString , int start , int length){
        StyleSpan styleSpan  = new StyleSpan(Typeface.BOLD);
        RadiusBackgroundSpan backgroundSpan = new RadiusBackgroundSpan(Color.parseColor("#F3B72C"),GBUtil.dpTo2px(this,5),Color.WHITE);
        spannableString.setSpan(styleSpan, start , start + length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(backgroundSpan, start , start + length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }

    void getData(){
         bid = getIntent().getStringExtra("bid");
         bidCount = getIntent().getIntExtra("bidCount",0);
         price = getIntent().getStringExtra("price");
    }
}